﻿using Microsoft.AspNetCore.Diagnostics;
using Microsoft.IdentityModel.Tokens;

namespace anydata.Handlers;
public class ErrorHanlder
{
    /// <summary>
    /// Executes the middleware.
    /// </summary>
    /// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
    /// <returns>A task that represents the execution of this middleware.</returns>
    public static async Task StatusCode(StatusCodeContext context)
    {
        var response = context.HttpContext.Response;
        await response.WriteToJsonAsync(new OperateResult()
        {
            success = false,
            data = new{},
            msg = $"request error,status code is {response.StatusCode}",
            code = response.StatusCode,
        });
    }
    /// <summary>
    /// Executes the middleware.
    /// </summary>
    /// <param name="app">The <see cref="IApplicationBuilder"/> for the current request.</param>
    /// <returns>A task that represents the execution of this middleware.</returns>
    public static void Exception(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
            if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
            {
                await context.Response.WriteToJsonAsync(new OperateResult()
                {
                    success = false,
                    data = new { },
                    msg = $"request error,status code is {404}",
                    code = 404,
                });
            }
            else if (exceptionHandlerPathFeature?.Error is SecurityTokenException)
            {
                await context.Response.WriteToJsonAsync(new OperateResult()
                {
                    success = false,
                    data = new { },
                    msg = $"access was denied.",
                    code = 401,
                });
            }
            else
            {
                await context.Response.WriteToJsonAsync(new OperateResult()
                {
                    success = false,
                    data = new { },
                    code = 500,
                    msg = $"Server is error, error message is {exceptionHandlerPathFeature?.Error?.Message ?? "unknown!"}"
                });
            }
        });
    }
}
